package com.light.mytext.mycustomview

import android.content.Context
import android.graphics.*
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import com.light.mytext.R

/**
 * 自定义可拖动矩形
 */
class RectangleView(
    context: Context?, /*indexX: Double, indexY: Double,*/
    fatherViewWidth: Int,
    fatherViewHeight: Int
) : View(context){
    var mPaintK: Paint? = null//默认边框
    var mPaintAngel: Paint? = null//四个角

    //是否开启抗锯齿
    private val antiAlias = true
    private val mArcWidth = 1f

    //父布局范围
    var mFatherViewWidth = fatherViewWidth
    var mFatherViewHeight = fatherViewHeight

    /**
     * 矩形view信息
     */
    //view中心点
    var centerIndexX = 0
    var centerIndexY = 0

    //默认宽高
    var viewHeight = 200
    var viewWidth = 250

    //背景宽高
    var aviewWidth = 0
    var aviewHeight = 0

    //双层中间隔
    var interval = 5

    //四个角的宽高
    var angelWidth = 20
    var angelinterval = 1//边角距离外层的距离
    var downX = 0
    var downY = 0

    var isMove = true
     var mCanvas: Canvas? = null
    init {
        centerIndexX = (viewWidth) / 2
        centerIndexY = (viewHeight) / 2
        initPaint()
    }

    fun initPaint() {
        /**
         * 默认边框
         */
        mPaintK = Paint()
        mPaintK!!.isAntiAlias = antiAlias
        // 设置画笔的样式，为FILL，FILL_OR_STROKE，或STROKE
        mPaintK!!.style = Paint.Style.STROKE
        // 设置画笔粗细
        mPaintK!!.strokeWidth = 2 * mArcWidth
        mPaintK!!.color = Color.WHITE
        mPaintK!!.textAlign = Paint.Align.CENTER
        /**
         * 四个角
         */
        mPaintAngel = Paint()
        mPaintAngel!!.isAntiAlias = antiAlias
        // 设置画笔的样式，为FILL，FILL_OR_STROKE，或STROKE
        mPaintAngel!!.style = Paint.Style.STROKE
        // 设置画笔粗细
        mPaintAngel!!.strokeWidth = 4 * mArcWidth
        mPaintAngel!!.color = Color.TRANSPARENT
        mPaintAngel!!.textAlign = Paint.Align.CENTER
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        mCanvas=canvas
        drawRectangular()
    }

    /**
     * 绘制矩形
     */
    fun drawRectangular() {
        mCanvas!!.drawColor(
            Color.TRANSPARENT,
            PorterDuff.Mode.CLEAR
        ) // 清除屏幕
        //绘制左边矩形
        val pathB = Path()
        pathB.moveTo(
            (centerIndexX + viewWidth / 2).toFloat(),
            (centerIndexY - viewHeight / 2).toFloat()
        )//起点  暂定右上角为起点
        pathB.lineTo(
            (centerIndexX - viewWidth / 2).toFloat(),
            (centerIndexY - viewHeight / 2).toFloat()
        )//左上角
        pathB.lineTo(
            (centerIndexX - viewWidth / 2).toFloat(),
            (centerIndexY + viewHeight / 2).toFloat()
        )//左下角
        pathB.lineTo(
            (centerIndexX + viewWidth / 2).toFloat(),
            (centerIndexY + viewHeight / 2).toFloat()
        )//右下角
        pathB.close() // 使这些点构成封闭的多边形
        mCanvas!!.drawPath(pathB, mPaintK!!)
        //绘制左边矩形
        val pathS = Path()
        pathS.moveTo(
            (centerIndexX + viewWidth / 2 - interval).toFloat(),
            (centerIndexY - viewHeight / 2 + interval).toFloat()
        )//起点  暂定右上角为起点
        pathS.lineTo(
            (centerIndexX - viewWidth / 2 + interval).toFloat(),
            (centerIndexY - viewHeight / 2 + interval).toFloat()
        )//左上角
        pathS.lineTo(
            (centerIndexX - viewWidth / 2 + interval).toFloat(),
            (centerIndexY + viewHeight / 2 - interval).toFloat()
        )//左下角
        pathS.lineTo(
            (centerIndexX + viewWidth / 2 - interval).toFloat(),
            (centerIndexY + viewHeight / 2 - interval).toFloat()
        )//右下角
        pathS.close() // 使这些点构成封闭的多边形
        mCanvas!!.drawPath(pathS, mPaintK!!)
        /**
         * 四个角边框
         */
        //右上角边框
        mCanvas!!.drawLine(
            (centerIndexX + viewWidth / 2 + angelinterval).toFloat(),
            (centerIndexY - viewHeight / 2 - angelinterval).toFloat(),
            (centerIndexX + viewWidth / 2 + angelinterval - angelWidth).toFloat(),
            (centerIndexY - viewHeight / 2 - angelinterval).toFloat(),
            mPaintAngel!!
        )
        mCanvas!!.drawLine(
            (centerIndexX + viewWidth / 2 + angelinterval).toFloat(),
            (centerIndexY - viewHeight / 2 - angelinterval).toFloat(),
            (centerIndexX + viewWidth / 2 + angelinterval).toFloat(),
            (centerIndexY - viewHeight / 2 - angelinterval + angelWidth).toFloat(),
            mPaintAngel!!
        )
        //左上角边框
        mCanvas!!.drawLine(
            (centerIndexX - viewWidth / 2 - angelinterval).toFloat(),
            (centerIndexY - viewHeight / 2 - angelinterval).toFloat(),
            (centerIndexX - viewWidth / 2 - angelinterval + angelWidth).toFloat(),
            (centerIndexY - viewHeight / 2 - angelinterval).toFloat(),
            mPaintAngel!!
        )
        mCanvas!!.drawLine(
            (centerIndexX - viewWidth / 2 - angelinterval).toFloat(),
            (centerIndexY - viewHeight / 2 - angelinterval).toFloat(),
            (centerIndexX - viewWidth / 2 - angelinterval).toFloat(),
            (centerIndexY - viewHeight / 2 - angelinterval + angelWidth).toFloat(),
            mPaintAngel!!
        )
        //左下角边框
        mCanvas!!.drawLine(
            (centerIndexX - viewWidth / 2 - angelinterval).toFloat(),
            (centerIndexY + viewHeight / 2 + angelinterval).toFloat(),
            (centerIndexX - viewWidth / 2 - angelinterval).toFloat(),
            (centerIndexY + viewHeight / 2 + angelinterval - angelWidth).toFloat(),
            mPaintAngel!!
        )
        mCanvas!!.drawLine(
            (centerIndexX - viewWidth / 2 - angelinterval).toFloat(),
            (centerIndexY + viewHeight / 2 + angelinterval).toFloat(),
            (centerIndexX - viewWidth / 2 - angelinterval + angelWidth).toFloat(),
            (centerIndexY + viewHeight / 2 + angelinterval).toFloat(),
            mPaintAngel!!
        )
        //右下角
        mCanvas!!.drawLine(
            (centerIndexX + viewWidth / 2 + angelinterval).toFloat(),
            (centerIndexY + viewHeight / 2 + angelinterval).toFloat(),
            (centerIndexX + viewWidth / 2 + angelinterval).toFloat(),
            (centerIndexY + viewHeight / 2 + angelinterval - angelWidth).toFloat(),
            mPaintAngel!!
        )
        mCanvas!!.drawLine(
            (centerIndexX + viewWidth / 2 + angelinterval).toFloat(),
            (centerIndexY + viewHeight / 2 + angelinterval).toFloat(),
            (centerIndexX + viewWidth / 2 + angelinterval - angelWidth).toFloat(),
            (centerIndexY + viewHeight / 2 + angelinterval).toFloat(),
            mPaintAngel!!
        )
    }

    /**
     * 取消选中
     */
    fun cancelChoose() {
        //重置选中paint
        mPaintK!!.reset()
        mPaintK!!.isAntiAlias = antiAlias
        // 设置画笔的样式，为FILL，FILL_OR_STROKE，或STROKE
        mPaintK!!.style = Paint.Style.STROKE
        // 设置画笔粗细
        mPaintK!!.strokeWidth = 2 * mArcWidth
        mPaintK!!.color = Color.WHITE
        mPaintK!!.textAlign = Paint.Align.CENTER
        //重置选中paint
        mPaintAngel!!.reset()
        mPaintAngel!!.isAntiAlias = antiAlias
        // 设置画笔的样式，为FILL，FILL_OR_STROKE，或STROKE
        mPaintAngel!!.style = Paint.Style.STROKE
        // 设置画笔粗细
        mPaintAngel!!.strokeWidth = 2 * mArcWidth
        mPaintAngel!!.color = Color.TRANSPARENT
        mPaintAngel!!.textAlign = Paint.Align.CENTER
        invalidate()
    }

    /**
     * 选中
     */
    fun Choose() {
        //重置选中paint
        mPaintK!!.reset()
        //把画笔颜色设置为透明，重绘
        mPaintK!!.isAntiAlias = antiAlias
        // 设置画笔的样式，为FILL，FILL_OR_STROKE，或STROKE
        mPaintK!!.style = Paint.Style.STROKE
        // 设置画笔粗细
        mPaintK!!.strokeWidth = 2 * mArcWidth
        mPaintK!!.color = resources.getColor(R.color.tv_color_00)
        mPaintK!!.textAlign = Paint.Align.CENTER
        //重置选中paint
        mPaintAngel!!.reset()
        mPaintAngel!!.isAntiAlias = antiAlias
        // 设置画笔的样式，为FILL，FILL_OR_STROKE，或STROKE
        mPaintAngel!!.style = Paint.Style.STROKE
        // 设置画笔粗细
        mPaintAngel!!.strokeWidth = 4 * mArcWidth
        mPaintAngel!!.color = resources.getColor(R.color.tv_color_00)
        mPaintAngel!!.textAlign = Paint.Align.CENTER
        invalidate()
    }

    /**
     * rawX  rawY 触摸点距离屏幕的距离
     *   x      y 触摸点距离view边界的距离
     */
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        var reDrawRatio = 0.3
        var reDrawX = (aviewWidth * reDrawRatio).toInt()
        var reDrawY = (aviewHeight * reDrawRatio).toInt()
        when (event!!.action) {
            MotionEvent.ACTION_DOWN -> {
                downX = event!!.x.toInt()
                downY = event.y.toInt()
                Log.i(
                    "Move1==",
                    "downX==" + event!!.x + "downY==" + event!!.y + "viewWidth==" + viewWidth + "viewHeight==" + viewHeight
                )
//                Log.i(
//                    "Move1==",
//                    "left==" + left + "right==" + right + "top==" +top + "bottom==" +bottom+"viewWidth=="+viewWidth+"viewHeight=="+viewHeight
//                )
                //触摸四个角时候为重绘（左上角，右上角,右下角,左下角）   其余为拖动
                var reDrawRatio = 0.3
                var reDrawX = (aviewWidth * reDrawRatio).toInt()
                var reDrawY = (aviewHeight * reDrawRatio).toInt()
                isMove = true//拖动
                isMove = !((downX in 0..reDrawX) && (downY in 0..reDrawY)||(downX in 0..reDrawX) && (downY in (aviewHeight-reDrawY)..aviewHeight)
                        ||(downX in (aviewWidth-reDrawX)..aviewWidth) && (downY in 0..reDrawY)||(downX in (aviewWidth-reDrawX)..aviewWidth) && (downY in (aviewHeight-reDrawY)..aviewHeight))
                Log.i("Move1==", "isMove==$isMove")
                Choose()
            }
            MotionEvent.ACTION_MOVE -> {
                //计算移动的距离
                var moveX: Int = event!!.x.toInt() - downX
                var moveY: Int = event!!.y.toInt() - downY
                if (isMove) {
                    //调用layout方法来重新放置它的位置
//                offsetLeftAndRight(moveX)
//                offsetTopAndBottom(moveY)
                    var l = left + moveX
                    var r = l + aviewWidth
                    var t = top + moveY
                    var b = t + aviewHeight
                    //划出左边边界
                    if (l < 0) {
                        l = 0
                        r = l + aviewWidth
                    }
                    //划出右边边界
                    if (r > mFatherViewWidth) {
                        r = mFatherViewWidth
                        l = r - aviewWidth
                    }
                    //划出上边边界
                    if (t < 0) {
                        t = 0
                        b = t + aviewHeight
                    }
                    //划出下边边界
                    if (b > mFatherViewHeight) {
                        b = mFatherViewHeight
                        t = b - aviewHeight
                    }
                    layout(l, t, r, b)
                    Log.i(
                        "Move==",
                        "neft==" + l + "ntop==" + t + "nright==" + r + "nbottom==" + b
                    )
                    val params: FrameLayout.LayoutParams = layoutParams as FrameLayout.LayoutParams
                    params.leftMargin = left
                    params.topMargin = top
                    layoutParams = params
                } else {//重绘
                    if((downX in 0..reDrawX) && (downY in 0..reDrawY)){//左上角  只改变 top和left的值
                        layout(left + moveX, top + moveY, right, bottom)
                    }
                    val params: FrameLayout.LayoutParams = layoutParams as FrameLayout.LayoutParams
                    params.leftMargin = left + moveX
                    params.topMargin = top + moveY
                    layoutParams = params

                    Log.i(
                        "Move2==",
                        "moveX=="+moveX+"moveY=="+moveY+"centerIndexX==" + centerIndexX + "centerIndexY==" + centerIndexY+ "viewWidth==" +viewWidth + "viewHeight==" + viewHeight
                    )
//                    drawRectangular()
                }
            }
            MotionEvent.ACTION_UP -> {
//                cancelChoose()
            }
        }
        return true
    }

    override fun hasFocus(): Boolean {
        Log.i("RectangleView==", super.hasFocus().toString())
        return super.hasFocus()
    }

    /**
     * 动态添加的话需要使用该方法设置View
     */
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(
            viewWidth + 50,
            viewHeight + 50
        )
    }

    /**
     * 以下两个方法设置View居中画布显示
     * 执行顺序（1）onMeasure（2）onSizeChanged
     */
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        //获取圆的相关参数    w即onMeasure中设置的  设置View居中画布显示
        centerIndexX = w / 2
        centerIndexY = h / 2
        aviewWidth = measuredWidth
        aviewHeight = measuredHeight
    }
}